前言
- 系统到了要实现赞和踩的阶段了;
REDIS
- 总是听nosql,但还真不懂啊原来nosql真的和传统数据库不一样;是依赖与传统中的集合来的
- redis的应用与集合的特性
- 赞与踩
我们实际存了一个hash,键呢就是内容类别+内容编号,比如是问题类,第几个,这样就确定是某一个集合,然后userId作为value,就将用户加入到这个集合中;既然是集合,自然可以去重,交集,并集啥的;
1234567891011121314151617181920212223242526272829303132333435363738394041public class LikeController {private static final Logger logger = LoggerFactory.getLogger(LikeController.class);LikeService likeService;HostHolder hostHolder;/*** 点赞函数,很简单的代码,判断一下用户登没登陆* 然后执行点赞操作,最后返回json串* @param commentId* @return*/"/like"}, method = {RequestMethod.POST})(path = {public String like(@RequestParam("commentId") int commentId) {if (hostHolder.getUser() == null) {return WendaUtil.getJSONString(999);}long likeCount = likeService.like(hostHolder.getUser().getId(), EntityType.ENTITY_COMMENT, commentId);return WendaUtil.getJSONString(0, String.valueOf(likeCount));}/*** 踩的操作* @param commentId* @return*/"/dislike"}, method = {RequestMethod.POST})(path = {public String dislike(@RequestParam("commentId") int commentId) {if (hostHolder.getUser() == null) {return WendaUtil.getJSONString(999);}long likeCount = likeService.disLike(hostHolder.getUser().getId(), EntityType.ENTITY_COMMENT, commentId);return WendaUtil.getJSONString(0, String.valueOf(likeCount));}}建立与redis的连接,然后重写各种方法
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980public class JedisAdapter implements InitializingBean {private JedisPool jedisPool;private static final Logger logger = LoggerFactory.getLogger(JedisAdapter.class);public static void print(int index, Object object) {System.out.println(String.format("%d,%s", index, object.toString()));}public void afterPropertiesSet() throws Exception {jedisPool = new JedisPool("redis://localhost:6379/10");}/*** 向redis中添加键值对* @param key* @param value* @return*/public long sadd(String key, String value) {Jedis jedis = null;try {jedis = jedisPool.getResource();return jedis.sadd(key, value);} catch (Exception e) {logger.error("发生异常");}finally {if (jedis != null) {jedis.close();}}return 0;}public long srem(String key, String value) {Jedis jedis = null;try {jedis = jedisPool.getResource();return jedis.srem(key, value);} catch (Exception e) {logger.error("发生异常");}finally {if (jedis != null) {jedis.close();}}return 0;}public long scard(String key) {Jedis jedis = null;try {jedis = jedisPool.getResource();return jedis.scard(key);} catch (Exception e) {logger.error("发生异常");}finally {if (jedis != null) {jedis.close();}}return 0;}public boolean sismember(String key,String value) {Jedis jedis = null;try {jedis = jedisPool.getResource();return jedis.sismember(key,value);} catch (Exception e) {logger.error("发生异常");}finally {if (jedis != null) {jedis.close();}}return false;}}